package cn.yangliu.comm;

import java.lang.reflect.Method;
import java.util.Objects;

import cn.yangliu.SecurityApplication;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 杨柳
 * @date 2019-06-01
 */
@RestControllerAdvice
public class ResponseBodyAdvice implements org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<?
            extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {

        Method method = methodParameter.getMethod();
        if (Objects.isNull(method)) {
            return o;
        }
        Class<?> declaringClass = method.getDeclaringClass();
        Package declaringClassPackage = declaringClass.getPackage();

        String declaringClassPackageString = declaringClassPackage.getName();

        Package mainClassPackage = SecurityApplication.class.getPackage();
        String mainClassPackageString = mainClassPackage.getName();

        if (!declaringClassPackageString.startsWith(mainClassPackageString)) {
            return o;
        }


        if (o instanceof JsonResult) {
            return o;
        }

        return JsonResult.getInstance(o);
    }
}
